package com.jp.knowledge.my.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.UploadLogic;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.my.util.MyUtil;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.MultipleImageUploader;
import com.jp.knowledge.util.ResultSubscriber;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * 认证
 *
 * @author gzejia 978862664@qq.com
 */
public class IdentifyActivity extends SlidingActivity implements MultipleImageUploader.ImageUploadCallBack, ResultSubscriber.OnResultListener, View.OnClickListener {

    private static final int SELECT_ID_CARD_CODE = 0x01;
    private static final int SELECT_BUSINESS_LICENSE_CODE = 0x02;
    private static final int COMMIT_AUTH = 0x03;

    /**
     * 公司认证
     */
    public static final int IDENTIFY_COMPANY = 1;
    /**
     * 班级认证
     */
    public static final int IDENTIFY_CLASS = 2;
    /**
     * 众创空间认证
     */
    public static final int IDENTIFY_PCREATION = 3;

    private int mIdentifyType = IDENTIFY_COMPANY;

    @ViewInject(R.id.identify_tv_input)
    private TextView mInputTv;
    @ViewInject(R.id.identify_tv_input_hind)
    private TextView mInputHindTv;
    @ViewInject(R.id.identify_lly_license)
    private View mLicenseLly;
    @ViewInject(R.id.identify_tv_license)
    private TextView mLicenseTv;
    @ViewInject(R.id.identify_tv_agree)
    private TextView mAgreeTv;
    @ViewInject(R.id.identify_tv_agree_content)
    private TextView mAgreeContentTv;

    @ViewInject(R.id.identify_edt_name)
    private EditText userName;
    @ViewInject(R.id.identify_edt_id)
    private EditText userIdCard;

    @ViewInject(R.id.identify_iv_id)
    private ImageView idCardImageView;
    @ViewInject(R.id.identify_iv_id_eg)
    private ImageView idCardExamples;

    @ViewInject(R.id.identify_iv_license)
    private ImageView businessLicenseImageView;
    @ViewInject(R.id.identify_iv_license_eg)
    private ImageView businessLicenseExample;

    @ViewInject(R.id.identify_cb_agree)
    private CheckBox agreeCb;
    private Dialog imagePreviewDialog;
    private int screenWidth;
    private int screenHeight;
    private PhotoViewAttacher.OnViewTapListener photpTapListener;

    private String idCardPath = "";
    private String businessLicensePath = "";

    @Override
    protected int getResourceId() {
        return R.layout.activity_identify;
    }

    @Override
    protected void init() {
        initTitle();
        initOthers();
    }

    private void initTitle() {
        topName.setText(mIdentifyType == IDENTIFY_COMPANY ? // 公司认证
                R.string.identify_tv_title_company : mIdentifyType == IDENTIFY_PCREATION ? // 众创空间认证
                R.string.identify_tv_title_pcreation : mIdentifyType == IDENTIFY_CLASS ? // 班级认证
                R.string.identify_tv_title_class : 0);
        topDesc.setVisibility(View.GONE);
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        rightIcon.setVisibility(View.GONE);
    }


    private void initOthers() {
        if(application.getUserData() != null)
            mIdentifyType = application.getUserData().getOrganizaType();

        if (mIdentifyType == IDENTIFY_COMPANY) {// 公司认证
            mLicenseTv.setText(R.string.identify_tv_company);
        } else if (mIdentifyType == IDENTIFY_PCREATION) {// 众创空间认证
            mLicenseTv.setText(R.string.identify_tv_pcreation);
        } else if (mIdentifyType == IDENTIFY_CLASS) {// 班级认证
            mLicenseLly.setVisibility(View.GONE);
            mInputTv.setText(R.string.identify_tv_input_student);
            mInputHindTv.setText(R.string.identify_tv_input_hind_student);
        }

        String agreeStr = getString(R.string.identify_tv_agree);
        String agreeContentStr = getString(R.string.identify_tv_agree_content);
        int blueColorRes = getResources().getColor(R.color.theme_color);
        mAgreeTv.setText(MyUtil.changeTextColor(agreeStr,
                blueColorRes, agreeStr.indexOf("《"), agreeStr.lastIndexOf("》") + 1));
        mAgreeContentTv.setText(MyUtil.changeTextColor(agreeContentStr,
                blueColorRes, agreeContentStr.indexOf("0"), agreeContentStr.lastIndexOf("2") + 1));

        idCardImageView.setOnClickListener(this);
        businessLicenseImageView.setOnClickListener(this);
        findViewById(R.id.identify_btn_request).setOnClickListener(this);
        businessLicenseExample.setOnClickListener(this);
        idCardExamples.setOnClickListener(this);
        leftIcon.setOnClickListener(this);

        imagePreviewDialog = new Dialog(this, R.style.custom_idalgo);
        screenWidth = getResources().getDisplayMetrics().widthPixels;
        screenHeight = getResources().getDisplayMetrics().heightPixels;
        photpTapListener = new PhotoViewAttacher.OnViewTapListener() {
            @Override
            public void onViewTap(View view, float x, float y) {
                imagePreviewDialog.dismiss();
            }
        };
    }

    private void showBigPhoto(int photoId){
        PhotoView imagePreviewPhotoView = new PhotoView(this);
        imagePreviewDialog.setContentView(imagePreviewPhotoView);
        imagePreviewPhotoView.setImageResource(photoId);
        ViewGroup.LayoutParams photoViewLayoutParams = imagePreviewPhotoView.getLayoutParams();
        photoViewLayoutParams.width = screenWidth;
        photoViewLayoutParams.height = screenHeight;
        imagePreviewPhotoView.setOnViewTapListener(photpTapListener);

        imagePreviewDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != RESULT_OK || data == null)
            return;
        if(requestCode == SELECT_ID_CARD_CODE) {
            idCardPath = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT).get(0);
            ImageLoadUtil.load(this, idCardPath, idCardImageView);
        } else if(requestCode == SELECT_BUSINESS_LICENSE_CODE){
            businessLicensePath = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT).get(0);
            ImageLoadUtil.load(this, businessLicensePath, businessLicenseImageView);
        }
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.identify_iv_id:// 身份证件照片
                PhotoPickerIntent idCardIntent = new PhotoPickerIntent(this);
                idCardIntent.setSelectModel(SelectModel.MULTI);
                idCardIntent.setMaxTotal(1);
                idCardIntent.setShowCarema(true);
                startActivityForResult(idCardIntent, SELECT_ID_CARD_CODE);
                overridePendingTransition(R.anim.anim_enter, 0);
                break;
            case R.id.identify_iv_id_eg:// 身份证件照片示例图
                showBigPhoto(R.mipmap.handheld_zoom);
                imagePreviewDialog.show();
                break;
            case R.id.identify_iv_license:// 营业执照照片
                PhotoPickerIntent businessLicenseIntent = new PhotoPickerIntent(this);
                businessLicenseIntent.setSelectModel(SelectModel.MULTI);
                businessLicenseIntent.setMaxTotal(1);
                businessLicenseIntent.setShowCarema(true);
                startActivityForResult(businessLicenseIntent, SELECT_BUSINESS_LICENSE_CODE);
                overridePendingTransition(R.anim.anim_enter, 0);
                break;
            case R.id.identify_iv_license_eg:// 营业执照照片示例图
                showBigPhoto(R.mipmap.enlarged_license);
                break;
            case R.id.identify_btn_request:// 申请认证
                if(userName.getText().toString().trim().length() == 0
                        || userIdCard.getText().toString().trim().length() != 18){
                    ToasUtil.toast(this, "请输入完整的信息后再提交");
                } else if(idCardPath == null || idCardPath.trim().length() == 0){
                    ToasUtil.toast(this, "请选择身份证照");
//                } else if((mIdentifyType != IDENTIFY_CLASS)
//                        && (businessLicensePath == null || businessLicensePath.trim().length() == 0)){
//                    ToasUtil.toast(this, "请选择营业执照");
                } else if(!agreeCb.isChecked()){
                    ToasUtil.toast(this, "请先阅读《竞品说认证协议》");
                } else{
                    loading.show();
                    List<MultipleImageUploader.ImageBean> imgDatas = new ArrayList<>();
                    MultipleImageUploader.ImageBean idCardBean = new MultipleImageUploader.ImageBean();
                    idCardBean.setPath(idCardPath);
                    String idCardKey = String.format("company/auth/%s/%s/%s",
                            application.getUserData().getCompanyId(),
                            UploadLogic.getTime(),
                            UploadLogic.getName());
                    idCardBean.setKey(idCardKey);
                    imgDatas.add(idCardBean);
                    if(businessLicensePath != null && businessLicensePath.trim().length() != 0) {
                        MultipleImageUploader.ImageBean imgBean = new MultipleImageUploader.ImageBean();
                        idCardBean.setPath(businessLicensePath);
                        String key = String.format("company/auth/%s/%s/%s",
                                application.getUserData().getCompanyId(),
                                UploadLogic.getTime(),
                                UploadLogic.getName());
                        idCardBean.setKey(key);
                        imgDatas.add(imgBean);
                    }
                    MultipleImageUploader imageUploader = new MultipleImageUploader(this);
                    imageUploader.setImageUploadCallBack(this);
                    imageUploader.addImages(imgDatas);
                    imageUploader.uploadImages();
                }
                break;
            case R.id.icon_left:// 返回
                finishSelf();
                break;
        }
    }
    private void finishSelf() {
        MyUtil.closeKeyword(this, userName);
        MyUtil.closeKeyword(this, userIdCard);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                onBackPressed();
            }
        }, 300);
    }

    /** 图片压缩上传相关回调方法 */
    @Override
    public void imageCompressFail(String key) {
        ToasUtil.toast(this, "抱歉，图片压缩失败，请稍后重试");
        loading.cancel();
    }
    @Override
    public void imageCompressSuccess(String key) {}
    @Override
    public void imageCompressComplete() {}
    @Override
    public void imageUploadFail(String key) {
        ToasUtil.toast(this, "抱歉，图片上传失败，请稍后重试");
        loading.cancel();
    }
    @Override
    public void imageUploadSuccess(String key, String resultKeys) {}
    @Override
    public void imageUploadComplete(List<String> resultKeys) {
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("id", application.getUserData().getCompanyId());
        param.addProperty("type", mIdentifyType);
        param.addProperty("name", userName.getText().toString());
        param.addProperty("code", userIdCard.getText().toString());
        param.addProperty("prove", resultKeys.get(0));
        if(resultKeys.size() > 1)
            param.addProperty("additional", resultKeys.get(1));
        HttpHelper.getInstance(this).authOrganize(param, COMMIT_AUTH, this);
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        loading.cancel();
    }
    @Override
    public void onError(int requestType) {
        loading.cancel();
        ToasUtil.toast(this, "抱歉，提交认证失败，请稍后重试");
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0) {
            ToasUtil.toast(mContext, data.getMessage());
        } else{
            ToasUtil.toast(this, "你的认证请求已提交，请耐心等待认证通过");
            this.finishSelf();
        }
    }
}
